package com.example.service.impl;

import com.example.dao.GoodsMapper;
import com.example.dao.OrderMapper;
import com.example.model.Goods;
import com.example.model.Order;
import com.example.model.Result;
import com.example.model.UserInfo;
import com.example.service.GoodsService;
import com.example.service.OrderService;
import com.example.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service("orderService")
public class OrderServiceImpl implements OrderService {
    Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    GoodsService goodsService;

    @Autowired
    UserService userService;

    OrderMapper orderMapper;

    @Resource
    public void setOrderMapper(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }


    @Override
    public Result commitOrder(Order order) {
        // 校验订单
//        checkOrder(order);
        // 生成预订单
        this.createOrder(order);
        // 扣减库存
//        goodsService.updateGoodsById(1, order.getGoodsId());
        // 扣减优惠券
        // 付费
//        userService.payOrder("asd");
        // 确定订单
        // 返回状态
        // 确认订单失败，发送消息
        // 返回失败状态
        return null;
    }

    @Override
    public void createOrder(Order order) {
        //  未确定
        order.setOrderStatus(0);
        //  未发货
        order.setShippingStatus(0);
        order.setCreateTime(new Date());
        orderMapper.insertSelective(order);
    }

    private boolean checkOrder(Order order) {
        // 判断订单是否为空
        if (null == order) {
            return false;
        }
        // 判断商品是否存在
        Goods goods = goodsService.getGoodsById(order.getGoodsId());
        if (null == goods) {
            return false;
        }
        // 判断用户是否存在
        UserInfo userInfo = userService.getUserInfoById(order.getUserId());
        if (null == userInfo) {
            return false;
        }
        // 判断商品库存
        // 判断商品单价是否合法

        return true;
    }
}
